package core

import (
	"fmt"
	"go-step/s9_cmdb/api/conf"
	"go-step/s9_cmdb/api/models"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	gorm_logger "gorm.io/gorm/logger"
	"gorm.io/gorm/schema"
)

// 定义db全局变量
var db *gorm.DB

func GetDB() *gorm.DB {
	return db
}

func InitDB() error {
	var err error
	dbConfig := conf.C().MySQL
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&multiStatements=true&parseTime=True&loc=Local",
		dbConfig.UserName,
		dbConfig.Password,
		dbConfig.Host,
		dbConfig.Port,
		dbConfig.Database)
	//dsn := "root:lSuszj85Tk@tcp(10.70.82.54:32306)/gin-blog-api?charset=utf8mb4&parseTime=True&loc=Local"
	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		SkipDefaultTransaction: false,
		NamingStrategy: schema.NamingStrategy{
			SingularTable: true, // 禁用表名加s
		},
		Logger:                                   gorm_logger.Default.LogMode(gorm_logger.Info), // 打印sql语句
		DisableAutomaticPing:                     false,
		DisableForeignKeyConstraintWhenMigrating: true, // 禁用创建外键约束
	})
	if err != nil {
		return err
	}

	sqlDB, err := db.DB()
	if err != nil {
		panic("mysql lost")
	}

	sqlDB.SetMaxOpenConns(100)
	sqlDB.SetMaxIdleConns(50)

	migrateDB()
	return nil
}

func migrateDB() {
	if conf.C().MySQL.AutoMigrate {
		err := db.AutoMigrate(&models.Host{})
		if err != nil {
			panic(err.Error())
		}
	}
}
